package com.hdax.dmw.pay.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.hdax.dmw.dtos.order.OrderDetailDto;
import com.hdax.dmw.entity.order.DmOrder;
import com.hdax.dmw.pay.alipay.AlipayConfig;
import com.hdax.dmw.pay.feign.OrderFeign;
import com.hdax.dmw.pay.service.ConfirmPayService;
import com.hdax.dmw.utils.Result;
import com.hdax.dmw.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConfirmPayServiceImpl implements ConfirmPayService {

    @Autowired
    private OrderFeign orderFeign;

    @Override
    public Result<OrderDetailDto> orderDetail(String orderNo) {
        DmOrder order = orderFeign.detaile(orderNo);
        OrderDetailDto dto = new OrderDetailDto();
        if(ObjectUtil.isNull(order)){

        }else{
            dto.setOrderNo(order.getOrderNo());
            dto.setItemName(order.getItemName());
            dto.setTotalAmount(order.getTotalAmount());
        }
        return ResultGenerator.genSuccessResult(dto);
    }

    @Override
    public String alipay(String orderNo) throws Exception {

        DmOrder order = orderFeign.detaile(orderNo);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getOrderNo();
        //付款金额，必填
        String total_amount = order.getTotalAmount().toString();
        //订单名称，必填
        String subject = order.getItemName();
        //商品描述，可空
        String body = "大觅网支付订单";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求  html -> form submit  script> document.forms[0].submit()
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return result;
    }
}
